<template>
  <view class="container">
    <!-- 使用 AdaptiveNavBar 组件 -->
    <AdaptiveNavBar 
      :showBack="true" 
      title="班期管理" 
      :showHome="false" 
      :showShadow="false" 
      text-color="#ffffff"
      :background-color="navBarBackgroundColor" 
    />

    <!-- 可滚动内容区域 -->
    <view class="content-area" :style="{ marginTop: $navbarUtil.getNavbarTotalHeightRpx() }">
    <scroll-view 
      class="scrollable-content" 
      scroll-y
      :enable-back-to-top="false"
      :scroll-with-animation="false"
      :bounces="false"
      :show-scrollbar="false"
    >
      <view class="calendar-container">
        <!-- 自定义日历组件 -->
        <CustomCalendar
          :key="`calendar-${currentSelectMode}-${selectedDatesA.length}-${selectedDatesB.length}`"
          :show="true"
          :selectMode="currentSelectMode"
          :defaultDateA="selectedDatesA"
          :defaultDateB="selectedDatesB"
          :minDate="minDate"
          :maxDate="maxDate"
          :monthNum="7"
          colorA="#1677FF"
          colorB="#52c41a"
          :disabledDate="disabledDates"
          :showTitle="true"
          :showSubtitle="true"
          :pageInline="true"
          :readonly="false"
          :businessType="businessType"
          :productType="productType"
          :isApplyCall="isApplyCall"
          :applicationDeadline="applicationDeadline"
          @dayClick="onDayClick"
          @change="onCalendarChange"
          @monthChange="onMonthChange"
        />
      </view>
    </scroll-view>
    </view>

    <!-- 固定在底部的区域 -->
    <view class="fixed-bottom">
      <button v-if="selectedDates.length > 0" class="confirm-btn" @tap="confirmSelect">确定</button>

      <!-- 滚动栏区域 -->
      <view class="scroll-container">
        <!-- 当前已选班期（用户标记-绿色） -->
        <view class="scroll-section">
          <view class="title-row">
            <text class="scroll-title">当前已选班期</text>
            <view class="expand-icon" @tap="toggleUserExpand" v-if="userButtonShow">
              <icon class="cuIcon-right" :class="{ fold: !showUserExpand }" type="" />
            </view>
          </view>

          <view v-if="!showUserExpand">
            <scroll-view class="scroll-view" scroll-x>
              <view class="scroll-item marked" v-for="item in formattedUserMarkedDates"
                :key="item.month + '-' + item.day">
                <text class="scroll-date">{{ item.month }}-{{ item.day }}</text>
                <text class="scroll-week">周{{ item.weekDay }}</text>
              </view>
            </scroll-view>
          </view>

          <view v-else class="expand-container">
            <view class="expand-row">
              <view class="expand-item marked" v-for="item in formattedUserMarkedDates"
                :key="item.month + '-' + item.day">
                <text class="expand-date">{{ item.month }}-{{ item.day }}</text>
                <text class="expand-week">周{{ item.weekDay }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import CustomCalendar from '@/components/CustomCalendar.vue'
import AdaptiveNavBar from '@/components/AdaptiveNavBar.vue'

export default {
  components: {
    CustomCalendar,
    AdaptiveNavBar
  },
  data() {
    return {
      StatusBar: 0,
      selectedDates: [],
      selectedDatesArray: [],
      selectedDatesA: [],
      selectedDatesB: [],
      currentSelectMode: 'A',
      showUserExpand: false,
      userButtonShow: true,
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      formattedUserMarkedDates: [],
      businessType: 1,
      isApplyCall: false,
      applicationDeadline: 0,
      productId: 0,
      productType: 0,
      periodList: [],
      outerPeriodList: [],
      isFromGetPeriodsFor: false, // 🔑 标记是否来自 getPeriodsFor 接口
      bStatePeriodsOriginal: [], // 🔑 getPeriodsFor 接口返回的 B 状态原始数据（用于对比）
      checkedPeriodArr: [] // 🔑 B状态返回的班期数据数组（整理后）
    }
  },

  computed: {
    navBarBackgroundColor() {
      return '#1677FF';
    },
    minDate() {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    maxDate() {
      const today = new Date();
      const maxDate = new Date(today);
      maxDate.setMonth(maxDate.getMonth() + 6);
      const year = maxDate.getFullYear();
      const month = String(maxDate.getMonth() + 1).padStart(2, '0');
      const day = String(maxDate.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 🔑 简化的禁用日期逻辑（专门用于 cooperation 页面）
    disabledDates() {
      return (date) => {
        const dateStr = `${date.year}-${String(date.month).padStart(2, '0')}-${String(date.date).padStart(2, '0')}`;
        
        // 🔑 如果来自 getPeriodsFor 接口，使用 B 模式逻辑
        if (this.isFromGetPeriodsFor) {
          // B模式：A模式的所有日期范围都可选，不在A状态列表中的日期禁用
          if (this.currentSelectMode === 'B') {
            // 检查是否在 outerPeriodList 中（A状态列表）
            if (this.outerPeriodList && this.outerPeriodList.length > 0) {
              const allPeriodDates = this.outerPeriodList.map(p => this.extractDateFromPeriod(p)).filter(d => d);
              // 如果在A状态列表中，则可选（不再根据 applicationDeadline 限制）
              if (allPeriodDates.includes(dateStr)) {
                return false; // 可选
              }
            }
            // 不在A状态列表中，禁用
            return true;
          }
          
          // A模式：如果日期已经在选中列表中，不禁用
          const isInSelectedDates = this.selectedDatesA.includes(dateStr) || this.selectedDatesB.includes(dateStr);
          if (isInSelectedDates) {
            return false;
          }
          
          // 检查是否在 outerPeriodList 中
          if (this.outerPeriodList && this.outerPeriodList.length > 0) {
            const allPeriodDates = this.outerPeriodList.map(p => this.extractDateFromPeriod(p)).filter(d => d);
            if (allPeriodDates.includes(dateStr)) {
              return false; // 在 A 状态列表中，可选
            }
          }
          
          // 不在 A 状态列表中，禁用
          return true;
        }
        
        // 其他情况：根据 applicationDeadline 判断（如果为 0，则不限制，所有日期都可选）
        // 当日不可选（无论 applicationDeadline 是多少，今天之前的日期都不可选）
        const now = new Date();
        const periodDate = new Date(dateStr);
        periodDate.setHours(0, 0, 0, 0);
        now.setHours(0, 0, 0, 0);
        
        if (periodDate <= now) {
          return true; // 今天之前的日期不可选
        }
        
        // 如果 applicationDeadline 为 0，则不限制，所有未来日期都可选
        if (this.applicationDeadline === 0 || !this.applicationDeadline) {
          return false; // 不限制，不禁用
        }
        
        // 根据 applicationDeadline 判断
        const deadlineDays = this.applicationDeadline;
        const deadlineTime = new Date(now);
        deadlineTime.setDate(now.getDate() + deadlineDays);
        deadlineTime.setHours(0, 0, 0, 0);
        
        const isSelectable = periodDate > deadlineTime;
        return !isSelectable;
      };
    }
  },

  onLoad(options) {
    uni.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#1677FF',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    });

    this.loadPeriodSelectParams();
    this.loadExistingSelectedDates();
    this.autoSetStates();
    this.formatMarkedDates();
    this.checkButtonShowStatus();
  },

  onReady() {
    uni.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#1677FF'
    });
    
    this.$nextTick(() => {
      this.$nextTick(() => {
        if (this.selectedDatesA.length === 0 && this.selectedDatesB.length === 0) {
          this.autoSetStates();
        }
        this.$forceUpdate();
      });
    });
  },

  methods: {
    // 加载已存在的选中日期
    loadExistingSelectedDates() {
      try {
        // 🔑 读取 cooperation.vue 中显示的班期列表（作为 B 状态的初始值）
        // 注意：cooperation.vue 中显示的所有班期都应该作为 B 状态的初始值
        const userSelectedPeriodsStr = uni.getStorageSync('userSelectedPeriodsForB');
        if (userSelectedPeriodsStr) {
          const userSelectedPeriods = JSON.parse(userSelectedPeriodsStr);
          console.log('📋 cooperationDateUtilPage - 读取 cooperation.vue 中显示的班期列表（B状态初始值）:', userSelectedPeriods);
          console.log('📋 cooperationDateUtilPage - 班期数量:', userSelectedPeriods.length);
          
          // 提取日期字符串，作为 B 状态的初始值
          // 注意：这里提取所有班期的日期，不管 isSelected 是否为 true
          const bStateDateStrings = userSelectedPeriods.map(item => {
            if (item.DateName) return item.DateName;
            if (item.Datevalue) return item.Datevalue;
            if (item.date) {
              // 如果是 MM/DD 格式，需要转换为 YYYY-MM-DD
              if (item.date.includes('/')) {
                const [month, day] = item.date.split('/');
                const today = new Date();
                return `${today.getFullYear()}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
              }
              return item.date;
            }
            // 🔑 如果有 availableDate，也尝试提取
            if (item.availableDate) {
              const { yearDate, monthDate, dayDate } = item.availableDate;
              if (yearDate && monthDate && dayDate) {
                const monthStr = String(monthDate).padStart(2, '0');
                const dayStr = String(dayDate).padStart(2, '0');
                return `${yearDate}-${monthStr}-${dayStr}`;
              }
            }
            return null;
          }).filter(d => d);
          
          // 设置 B 状态的初始值（cooperation.vue 中显示的所有班期）
          if (bStateDateStrings && bStateDateStrings.length > 0) {
            this.selectedDatesB = [...bStateDateStrings];
            console.log('📋 cooperationDateUtilPage - 设置 B 状态初始值（cooperation.vue 中显示的所有班期）:', this.selectedDatesB);
            console.log('📋 cooperationDateUtilPage - B 状态初始值数量:', this.selectedDatesB.length);
          }
          
          uni.removeStorageSync('userSelectedPeriodsForB');
        }
        
        // 读取所有班期数据（用于兼容）
        const existingDatesStr = uni.getStorageSync('existingSelectedDates');
        if (existingDatesStr) {
          const existingDates = JSON.parse(existingDatesStr);
          const dateStrings = existingDates.map(item => {
            if (item.DateName) return item.DateName;
            if (item.Datevalue) return item.Datevalue;
            if (item.date) {
              if (item.date.includes('/')) {
                const [month, day] = item.date.split('/');
                const today = new Date();
                return `${today.getFullYear()}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
              }
              return item.date;
            }
            return null;
          }).filter(d => d);

          // 如果 B 状态还没有值，使用所有日期作为 A 状态
          if (dateStrings && dateStrings.length > 0 && this.selectedDatesB.length === 0) {
            dateStrings.forEach(dateStr => {
              if (!this.selectedDatesA.includes(dateStr)) {
                this.selectedDatesA.push(dateStr);
              }
            });
          }

          this.selectedDatesArray = dateStrings;
          this.selectedDates = dateStrings;
          uni.removeStorageSync('existingSelectedDates');
        }
      } catch (e) {
        console.error('读取已存在日期失败:', e);
      }
    },

    // 读取班期选择参数
    loadPeriodSelectParams() {
      try {
        const paramsStr = uni.getStorageSync('periodSelectParams');
        if (paramsStr) {
          const params = JSON.parse(paramsStr);
          this.businessType = params.businessType || 1;
          this.isApplyCall = params.isApplyCall || false;
          // 🔑 applicationDeadline 如果没传，应该为 0，不取默认值 15
          this.applicationDeadline = params.applicationDeadline !== undefined && params.applicationDeadline !== null ? params.applicationDeadline : 0;
          this.productId = params.productId || 0;
          this.productType = Number(params.productType) || 0;
          // 🔑 检查是否来自 getPeriodsFor 接口
          this.isFromGetPeriodsFor = params.isBMode === true || params.isBMode === 'true';
          console.log('📋 cooperationDateUtilPage - 读取参数:', params, 'isFromGetPeriodsFor:', this.isFromGetPeriodsFor);
          uni.removeStorageSync('periodSelectParams');
        }
      } catch (e) {
        console.error('读取班期选择参数失败:', e);
      }

      // 读取班期列表
      try {
        const periodListStr = uni.getStorageSync('periodList');
        if (periodListStr) {
          this.periodList = JSON.parse(periodListStr);
          console.log('📋 cooperationDateUtilPage - 读取 periodList:', this.periodList);
        }
      } catch (e) {
        console.error('读取班期列表失败:', e);
      }
      
      // 读取外层班期列表
      try {
        const outerPeriodListStr = uni.getStorageSync('outerPeriodList');
        if (outerPeriodListStr) {
          this.outerPeriodList = JSON.parse(outerPeriodListStr);
          console.log('📋 cooperationDateUtilPage - 读取 outerPeriodList:', this.outerPeriodList);
          console.log('📋 cooperationDateUtilPage - outerPeriodList 数量:', this.outerPeriodList ? this.outerPeriodList.length : 0);
          if (this.outerPeriodList && this.outerPeriodList.length > 0) {
            console.log('📋 cooperationDateUtilPage - outerPeriodList 第一个元素示例:', this.outerPeriodList[0]);
          }
        } else {
          console.warn('⚠️ cooperationDateUtilPage - 未找到 outerPeriodList 数据');
        }
      } catch (e) {
        console.error('读取外层班期列表失败:', e);
      }
      
      // 🔑 读取 getPeriodsFor 接口返回的 B 状态原始数据
      try {
        const bStatePeriodsOriginalStr = uni.getStorageSync('bStatePeriodsOriginal');
        if (bStatePeriodsOriginalStr) {
          this.bStatePeriodsOriginal = JSON.parse(bStatePeriodsOriginalStr);
          console.log('📋 cooperationDateUtilPage - 读取 getPeriodsFor 接口返回的 B 状态原始数据:', this.bStatePeriodsOriginal);
          console.log('📋 cooperationDateUtilPage - bStatePeriodsOriginal 数量:', this.bStatePeriodsOriginal ? this.bStatePeriodsOriginal.length : 0);
          if (this.bStatePeriodsOriginal && this.bStatePeriodsOriginal.length > 0) {
            console.log('📋 cooperationDateUtilPage - bStatePeriodsOriginal 第一个元素示例:', this.bStatePeriodsOriginal[0]);
          }
        } else {
          console.warn('⚠️ cooperationDateUtilPage - 未找到 bStatePeriodsOriginal 数据');
        }
      } catch (e) {
        console.error('读取 B 状态原始数据失败:', e);
      }
    },
    
    // 自动设置A和B状态
    autoSetStates() {
      // 🔑 如果来自 getPeriodsFor 接口，使用 B 模式
      if (this.isFromGetPeriodsFor) {
        console.log('📋 cooperationDateUtilPage - 来自 getPeriodsFor 接口，使用 B 模式');
        
        // A状态：从 outerPeriodList 提取日期
        let outerPeriodDates = [];
        if (this.outerPeriodList && this.outerPeriodList.length > 0) {
          console.log('📋 cooperationDateUtilPage - outerPeriodList 原始数据:', this.outerPeriodList);
          this.outerPeriodList.forEach((period, index) => {
            let dateStr = this.extractDateFromPeriod(period);
            console.log(`📋 cooperationDateUtilPage - 提取第 ${index + 1} 个班期日期:`, {
              period,
              dateStr,
              hasDateName: !!period.DateName,
              hasAvailableDate: !!period.availableDate
            });
            if (dateStr) {
              outerPeriodDates.push(dateStr);
            } else {
              console.warn(`⚠️ cooperationDateUtilPage - 第 ${index + 1} 个班期无法提取日期:`, period);
            }
          });
          console.log('📋 父班期数据列表:', outerPeriodDates);
        } else {
          console.warn('⚠️ cooperationDateUtilPage - outerPeriodList 为空或不存在');
        }
        this.selectedDatesA = outerPeriodDates;
        
        // B状态：优先使用从 cooperation.vue 传递过来的用户已选中的班期列表
        // 如果没有，则从 periodList 提取已选中的日期
        let currentPeriodSelectedDates = [];
        
        // 🔑 如果已经有从 cooperation.vue 传递过来的 B 状态初始值，直接使用
        if (this.selectedDatesB && this.selectedDatesB.length > 0) {
          console.log('📋 已调用的班期列表:', this.selectedDatesB);
          currentPeriodSelectedDates = [...this.selectedDatesB];
        } else if (this.periodList && this.periodList.length > 0) {
          // 否则从 periodList 提取已选中的日期
          this.periodList.forEach(period => {
            let dateStr = this.extractDateFromPeriod(period);
            if (dateStr) {
              // 如果班期对象中有 isSelected 属性且为 true，则添加到已选中列表
              if (period.isSelected === true || period.isSelected === 'true') {
                currentPeriodSelectedDates.push(dateStr);
              }
            }
          });
        }
        this.selectedDatesB = currentPeriodSelectedDates;
        
        // 设置为 B 模式
        this.currentSelectMode = 'B';
        
        console.log('📋 cooperationDateUtilPage - A状态:', this.selectedDatesA.length, '个班期');
        console.log('📋 cooperationDateUtilPage - B状态:', this.selectedDatesB.length, '个班期');
      } else {
        // 其他情况：根据业务类型和产品类型设置
        const productTypeNum = Number(this.productType) || 0;
        
        if (this.businessType === 1) {
          // 一类商家：所有班期都是A状态
          const currentPeriodDates = [];
          if (this.periodList && this.periodList.length > 0) {
            this.periodList.forEach(period => {
              let dateStr = this.extractDateFromPeriod(period);
              if (dateStr) {
                currentPeriodDates.push(dateStr);
              }
            });
          }
          this.selectedDatesA = currentPeriodDates;
          this.selectedDatesB = [];
          this.currentSelectMode = 'A';
        } else if (this.businessType === 2) {
          // 二类商家
          let outerPeriodDates = [];
          if (this.outerPeriodList && this.outerPeriodList.length > 0) {
            this.outerPeriodList.forEach(period => {
              let dateStr = this.extractDateFromPeriod(period);
              if (dateStr) {
                outerPeriodDates.push(dateStr);
              }
            });
          }
          this.selectedDatesA = outerPeriodDates.length > 0 ? outerPeriodDates : [];
          
          if (productTypeNum === 4) {
            // 组团业务：B模式
            let currentPeriodSelectedDates = [];
            if (this.periodList && this.periodList.length > 0) {
              this.periodList.forEach(period => {
                let dateStr = this.extractDateFromPeriod(period);
                if (dateStr && (period.isSelected === true || period.isSelected === 'true')) {
                  currentPeriodSelectedDates.push(dateStr);
                }
              });
            }
            this.selectedDatesB = currentPeriodSelectedDates;
            this.currentSelectMode = 'B';
          } else {
            // 其他：A模式
            const currentPeriodDates = [];
            if (this.periodList && this.periodList.length > 0) {
              this.periodList.forEach(period => {
                let dateStr = this.extractDateFromPeriod(period);
                if (dateStr) {
                  currentPeriodDates.push(dateStr);
                }
              });
            }
            currentPeriodDates.forEach(date => {
              if (!this.selectedDatesA.includes(date)) {
                this.selectedDatesA.push(date);
              }
            });
            this.selectedDatesB = [];
            this.currentSelectMode = 'A';
          }
        } else if (this.businessType === 3) {
          // 三类商家
          let outerPeriodDates = [];
          if (this.outerPeriodList && this.outerPeriodList.length > 0) {
            this.outerPeriodList.forEach(period => {
              let dateStr = this.extractDateFromPeriod(period);
              if (dateStr) {
                outerPeriodDates.push(dateStr);
              }
            });
          }
          this.selectedDatesA = outerPeriodDates;
          
          if (productTypeNum === 5) {
            // 研学活动：B模式
            let currentPeriodSelectedDates = [];
            if (this.periodList && this.periodList.length > 0) {
              this.periodList.forEach(period => {
                let dateStr = this.extractDateFromPeriod(period);
                if (dateStr && (period.isSelected === true || period.isSelected === 'true')) {
                  currentPeriodSelectedDates.push(dateStr);
                }
              });
            }
            this.selectedDatesB = currentPeriodSelectedDates;
          } else {
            this.selectedDatesB = [];
          }
          this.currentSelectMode = 'B';
        } else {
          // 默认：A状态
          const currentPeriodDates = [];
          if (this.periodList && this.periodList.length > 0) {
            this.periodList.forEach(period => {
              let dateStr = this.extractDateFromPeriod(period);
              if (dateStr) {
                currentPeriodDates.push(dateStr);
              }
            });
          }
          this.selectedDatesA = currentPeriodDates;
          this.selectedDatesB = [];
          this.currentSelectMode = 'A';
        }
      }

      // 更新兼容字段
      this.selectedDates = [...this.selectedDatesA, ...this.selectedDatesB];
      this.selectedDatesArray = [...this.selectedDatesA, ...this.selectedDatesB];
      
      console.log('📋 cooperationDateUtilPage - 自动设置状态完成 - A状态:', this.selectedDatesA.length, 'B状态:', this.selectedDatesB.length, '模式:', this.currentSelectMode);
    },
    
    // 从班期对象中提取日期字符串
    extractDateFromPeriod(period) {
      if (!period) return null;
      
      let dateStr = null;
      
      // 🔑 优先检查 DateName（转换后的格式）
      if (period.DateName) {
        dateStr = period.DateName;
      } 
      // 🔑 检查 Datevalue
      else if (period.Datevalue) {
        dateStr = period.Datevalue;
      } 
      // 🔑 检查 date 字段
      else if (period.date) {
        if (period.date.includes('/')) {
          const [month, day] = period.date.split('/');
          const today = new Date();
          dateStr = `${today.getFullYear()}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
        } else {
          dateStr = period.date;
        }
      }
      // 🔑 检查 availableDate 格式（原始数据格式）
      else if (period.availableDate) {
        const { yearDate, monthDate, dayDate } = period.availableDate;
        if (yearDate && monthDate && dayDate) {
          const monthStr = String(monthDate).padStart(2, '0');
          const dayStr = String(dayDate).padStart(2, '0');
          dateStr = `${yearDate}-${monthStr}-${dayStr}`;
        }
      }
      
      return dateStr;
    },

    // 日历日期点击事件
    onDayClick(dateStr, status, action) {
      console.log('日期点击:', dateStr, '状态:', status, '操作:', action);
    },
    
    // 日历变化事件
    onCalendarChange(selectedA, selectedB) {
      console.log('日历变化 - A状态:', selectedA, 'B状态:', selectedB);
      this.selectedDatesA = selectedA;
      this.selectedDatesB = selectedB;
      
      this.selectedDates = [...selectedA, ...selectedB];
      this.selectedDatesArray = [...selectedA, ...selectedB];
      
      this.formatMarkedDates();
      this.checkButtonShowStatus();
    },
    
    // 月份切换事件
    onMonthChange(year, month) {
      console.log('月份切换:', year, month);
    },

    // 切换用户标记展开状态
    toggleUserExpand() {
      this.showUserExpand = !this.showUserExpand;
    },

    // 格式化标记日期
    formatMarkedDates() {
      const formatDate = (dateStr) => {
        try {
          const d = new Date(dateStr);
          return {
            year: d.getFullYear(),
            month: d.getMonth() + 1,
            day: d.getDate(),
            weekDay: this.weekDays[d.getDay()]
          };
        } catch (e) {
          console.error('日期格式化失败:', dateStr, e);
          return null;
        }
      };

      // 根据当前选择模式决定显示哪个列表
      let dates = [];
      if (this.currentSelectMode === 'A') {
        dates = Array.isArray(this.selectedDatesA) ? this.selectedDatesA : [];
      } else if (this.currentSelectMode === 'B') {
        dates = Array.isArray(this.selectedDatesB) ? this.selectedDatesB : [];
      } else {
        const allSelectedDates = [...new Set([...this.selectedDatesA, ...this.selectedDatesB])];
        dates = Array.isArray(allSelectedDates) ? allSelectedDates : [allSelectedDates];
      }

      let formatted = dates.filter(d => d && d !== '' && d !== undefined).map(formatDate).filter(d => d !== null);

      // 对日期进行排序
      formatted.sort((a, b) => {
        if (a.year !== b.year) {
          return a.year - b.year;
        }
        if (a.month !== b.month) {
          return a.month - b.month;
        }
        return a.day - b.day;
      });

      this.formattedUserMarkedDates = formatted;
    },

    // 检查按钮是否需要显示
    checkButtonShowStatus() {
      const { formattedUserMarkedDates } = this;
      const { windowWidth } = uni.getSystemInfoSync();
      const itemWidth = 104 + 15;

      const userTotalWidth = formattedUserMarkedDates.length * itemWidth;
      this.userButtonShow = userTotalWidth > windowWidth;
    },

    // 确认选择
    confirmSelect() {
      // 🔑 如果来自 getPeriodsFor 接口，使用 B 模式逻辑
      if (this.isFromGetPeriodsFor) {
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('📋 cooperationDateUtilPage - 确认选择（B模式）');
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        
        // 🔑 使用 B 状态返回的日期，与 getPeriodsFor 接口返回的原始数据做对比，找出符合的完整数据
        let allPeriodDates = [];
        
        // 如果有 getPeriodsFor 接口返回的 B 状态原始数据，使用它来对比
        if (this.bStatePeriodsOriginal && this.bStatePeriodsOriginal.length > 0) {
          console.log('📋 使用 getPeriodsFor 接口返回的 B 状态原始数据做对比');
          
          // 遍历 B 状态返回的日期
          this.selectedDatesB.forEach(dateStr => {
            // 在 getPeriodsFor 接口返回的原始数据中查找匹配的班期
            const matchedPeriod = this.bStatePeriodsOriginal.find(period => {
              // 提取原始数据中的日期
              if (period.availableDate) {
                const { yearDate, monthDate, dayDate } = period.availableDate;
                if (yearDate && monthDate && dayDate) {
                  const monthStr = String(monthDate).padStart(2, '0');
                  const dayStr = String(dayDate).padStart(2, '0');
                  const periodDateStr = `${yearDate}-${monthStr}-${dayStr}`;
                  return periodDateStr === dateStr;
                }
              }
              return false;
            });
            
            if (matchedPeriod) {
              // 找到匹配的班期，使用原始数据的完整信息
              const { yearDate, monthDate, dayDate } = matchedPeriod.availableDate;
              const monthStr = String(monthDate).padStart(2, '0');
              const dayStr = String(dayDate).padStart(2, '0');
              const date = new Date(yearDate, monthDate - 1, dayDate);
              const weekDay = date.getDay();
              const weekDayNames = ['日', '一', '二', '三', '四', '五', '六'];
              
              // 🔑 periodId 优先级：本身的 periodId > 上级的 periodId > 日期保底
              let finalPeriodId = null;
              // 1. 优先使用本身的 periodId（matchedPeriod 中的 periodId 或 id）
              if (matchedPeriod.periodId) {
                finalPeriodId = matchedPeriod.periodId;
              } else if (matchedPeriod.id) {
                finalPeriodId = matchedPeriod.id;
              } else {
                // 2. 如果本身没有，尝试从 outerPeriodList（A状态，上级数据）中查找
                if (this.outerPeriodList && this.outerPeriodList.length > 0) {
                  const parentPeriod = this.outerPeriodList.find(p => {
                    const pDateStr = this.extractDateFromPeriod(p);
                    return pDateStr === dateStr;
                  });
                  if (parentPeriod) {
                    finalPeriodId = parentPeriod.periodId || parentPeriod.id;
                  }
                }
                // 3. 如果上级也没有，使用日期保底
                if (!finalPeriodId) {
                  finalPeriodId = `${yearDate}${monthStr}${dayStr}`;
                }
              }
              
              // 🔑 使用 getPeriodsFor 接口返回的原始数据，保留所有字段
              // 🔑 注意：不设置 isSelected，因为这是日期选择页面的多选状态，不应该影响合作申请管理页面的单选状态
              allPeriodDates.push({
                ...matchedPeriod, // 🔑 保留原始数据的所有字段
                DateName: dateStr,
                Datevalue: dateStr,
                Datevalue1: `${monthStr}/${dayStr}`,
                date: `${monthStr}/${dayStr}`,
                WeekName: matchedPeriod.availableDate?.weekDate || `周${weekDayNames[weekDay]}`,
                id: finalPeriodId,
                periodId: finalPeriodId,
                mycheck: true,
                is: true
                // 🔑 不设置 isSelected，由 cooperation.vue 自己管理选中状态
              });
            } else {
              // 🔑 如果找不到匹配的班期，基于日期字符串创建新的班期对象
              // 新增的班期就是提出申请的班期，status 应该为 0（申请中）
              console.warn(`⚠️ 未在 getPeriodsFor 接口返回的数据中找到日期 ${dateStr} 对应的班期，将基于日期创建新对象（status=0）`);
              const [year, month, day] = dateStr.split('-').map(Number);
              const date = new Date(year, month - 1, day);
              const weekDay = date.getDay();
              const weekDayNames = ['日', '一', '二', '三', '四', '五', '六'];
              const monthStr = String(month).padStart(2, '0');
              const dayStr = String(day).padStart(2, '0');
              
              // 🔑 periodId 优先级：上级的 periodId > 日期保底
              // 1. 尝试从 outerPeriodList（A状态，上级数据）中查找
              let finalPeriodId = null;
              if (this.outerPeriodList && this.outerPeriodList.length > 0) {
                const parentPeriod = this.outerPeriodList.find(p => {
                  const pDateStr = this.extractDateFromPeriod(p);
                  return pDateStr === dateStr;
                });
                if (parentPeriod) {
                  finalPeriodId = parentPeriod.periodId || parentPeriod.id;
                }
              }
              // 2. 如果上级也没有，使用日期保底
              if (!finalPeriodId) {
                finalPeriodId = `${year}${monthStr}${dayStr}`;
              }
              
              allPeriodDates.push({
                DateName: dateStr,
                Datevalue: dateStr,
                Datevalue1: `${monthStr}/${dayStr}`,
                date: `${monthStr}/${dayStr}`,
                WeekName: `周${weekDayNames[weekDay]}`,
                id: finalPeriodId,
                periodId: finalPeriodId,
                mycheck: true,
                is: true,
                // 🔑 不设置 isSelected，由 cooperation.vue 自己管理选中状态
                status: 0, // 🔑 新增的班期就是提出申请的班期，status=0（申请中）
                isSelectable: false, // 🔑 status=0 时不可选（申请中）
                availableDate: {
                  yearDate: year,
                  monthDate: month,
                  dayDate: day,
                  weekDate: weekDayNames[weekDay]
                }
              });
            }
          });
        } else {
          // 如果没有 getPeriodsFor 接口返回的原始数据，使用 A 状态数据（兼容旧逻辑）
          console.log('📋 未找到 getPeriodsFor 接口返回的 B 状态原始数据，使用 A 状态数据');
          if (this.outerPeriodList && this.outerPeriodList.length > 0) {
            allPeriodDates = this.outerPeriodList.map(period => {
              const dateStr = this.extractDateFromPeriod(period);
              if (!dateStr) return null;
              
              const [year, month, day] = dateStr.split('-').map(Number);
              const date = new Date(year, month - 1, day);
              const weekDay = date.getDay();
              const weekDayNames = ['日', '一', '二', '三', '四', '五', '六'];
              
              // 检查这个日期是否在B状态中
              const isSelected = this.selectedDatesB.includes(dateStr);
              
              const periodId = period.id || period.periodId || `${year}${String(day).padStart(2, '0')}${String(month).padStart(2, '0')}`;
              
              return {
                ...period,
                DateName: period.DateName || dateStr,
                Datevalue: period.Datevalue || dateStr,
                Datevalue1: period.Datevalue1 || `${String(month).padStart(2, '0')}/${String(day).padStart(2, '0')}`,
                date: period.date || `${String(month).padStart(2, '0')}/${String(day).padStart(2, '0')}`,
                WeekName: period.WeekName || `周${weekDayNames[weekDay]}`,
                id: periodId,
                periodId: periodId,
                mycheck: true,
                is: isSelected
                // 🔑 不设置 isSelected，由 cooperation.vue 自己管理选中状态
              };
            }).filter(p => p !== null);
          }
        }
        
        // 🔑 打印返回的数据，对照 getPeriodsFor 接口返回的原始数据
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('📋 cooperationDateUtilPage - 确认选择（B模式）返回数据');
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('📋 getPeriodsFor 接口返回的 B 状态原始数据（bStatePeriodsOriginal）:');
        console.log('   总数:', this.bStatePeriodsOriginal ? this.bStatePeriodsOriginal.length : 0, '个班期');
        if (this.bStatePeriodsOriginal && this.bStatePeriodsOriginal.length > 0) {
          this.bStatePeriodsOriginal.forEach((period, index) => {
            const ad = period.availableDate || {};
            const dateStr = ad.yearDate && ad.monthDate && ad.dayDate 
              ? `${ad.yearDate}-${String(ad.monthDate).padStart(2, '0')}-${String(ad.dayDate).padStart(2, '0')}`
              : '';
            console.log(`   [${index + 1}] getPeriodsFor 原始数据:`, {
              id: period.id,
              periodId: period.periodId,
              dateStr: dateStr,
              availableDate: period.availableDate,
              status: period.status,
              applicationDeadline: period.applicationDeadline,
              fullData: period
            });
          });
        }
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('📋 B状态返回的班期列表（selectedDatesB）:');
        console.log('   总数:', this.selectedDatesB.length, '个班期');
        this.selectedDatesB.forEach((dateStr, index) => {
          console.log(`   [${index + 1}] ${dateStr}`);
        });
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('📋 B状态返回的班期数据（allPeriodDates）- 对照 getPeriodsFor 接口原始数据:');
        console.log('   总数:', allPeriodDates.length, '个班期');
        if (allPeriodDates && allPeriodDates.length > 0) {
          allPeriodDates.forEach((period, index) => {
            // 🔑 对照 getPeriodsFor 接口返回的原始数据
            const originalPeriod = this.bStatePeriodsOriginal && this.bStatePeriodsOriginal.length > 0 
              ? this.bStatePeriodsOriginal.find(p => {
                  const ad = p.availableDate || {};
                  if (ad.yearDate && ad.monthDate && ad.dayDate) {
                    const monthStr = String(ad.monthDate).padStart(2, '0');
                    const dayStr = String(ad.dayDate).padStart(2, '0');
                    const pDateStr = `${ad.yearDate}-${monthStr}-${dayStr}`;
                    return pDateStr === period.DateName;
                  }
                  return false;
                })
              : null;
            
            console.log(`   [${index + 1}] B状态返回的班期:`);
            console.log(`      日期: ${period.DateName}`);
            console.log(`      星期: ${period.WeekName}`);
            console.log(`      periodId: ${period.periodId || period.id}`);
            // 🔑 不再打印 isSelected，因为这是日期选择页面的多选状态，不应该影响合作申请管理页面的单选状态
            console.log(`      完整数据:`, period);
            console.log(`      🔑 从 getPeriodsFor 接口获取的所有字段:`, {
              // 列出所有从 getPeriodsFor 接口获取的字段
              periodId: period.periodId || period.id,
              DateName: period.DateName,
              WeekName: period.WeekName,
              availableDate: period.availableDate,
              status: period.status,
              applicationDeadline: period.applicationDeadline,
              id: period.id,
              // 显示所有字段的键
              allKeys: Object.keys(period)
            });
            if (originalPeriod) {
              console.log(`      ✅ 在 getPeriodsFor 接口原始数据中找到对应数据:`, {
                原始数据id: originalPeriod.id,
                原始数据periodId: originalPeriod.periodId,
                原始数据status: originalPeriod.status,
                原始数据applicationDeadline: originalPeriod.applicationDeadline,
                原始数据所有字段: Object.keys(originalPeriod),
                原始数据完整数据: originalPeriod
              });
              // 🔑 对比原始数据和返回数据，确保所有字段都被保留
              console.log(`      🔍 数据对比:`);
              const missingFields = [];
              Object.keys(originalPeriod).forEach(key => {
                if (!(key in period)) {
                  missingFields.push(key);
                }
              });
              if (missingFields.length > 0) {
                console.log(`      ⚠️ B状态返回数据中缺少的字段:`, missingFields);
              } else {
                console.log(`      ✅ B状态返回数据包含了 getPeriodsFor 接口原始数据的所有字段`);
              }
            } else {
              console.log(`      ⚠️ 未在 getPeriodsFor 接口原始数据中找到对应数据`);
            }
            console.log('   ────────────────────────────────────────');
          });
        }
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('📋 统计信息:');
        console.log('   - getPeriodsFor 接口原始数据总数:', this.bStatePeriodsOriginal ? this.bStatePeriodsOriginal.length : 0, '个班期');
        console.log('   - B状态返回班期总数:', allPeriodDates.length, '个班期');
        // 🔑 不再统计 isSelected，因为这是日期选择页面的多选状态，不应该影响合作申请管理页面的单选状态
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('📋 B状态返回的班期数据数组（整理后）:');
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        // 🔑 整理成数组格式
        // 🔑 注意：不包含 isSelected 字段，因为这是日期选择页面的多选状态，不应该影响合作申请管理页面的单选状态
        const formattedPeriodArray = allPeriodDates.map((period, index) => {
          return {
            index: index + 1,
            DateName: period.DateName,
            WeekName: period.WeekName,
            periodId: period.periodId || period.id,
            id: period.id,
            // 🔑 不包含 isSelected 字段，由 cooperation.vue 自己管理选中状态
            // 从 getPeriodsFor 接口原始数据中获取的字段
            availableDate: period.availableDate,
            status: period.status,
            applicationDeadline: period.applicationDeadline,
            // 其他可能的字段
            fullData: period
          };
        });
        console.log('📋 整理后的数组（formattedPeriodArray）:');
        console.log(formattedPeriodArray);
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('📋 数组 JSON 格式:');
        console.log(JSON.stringify(formattedPeriodArray, null, 2));
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        
        // 🔑 将整理后的数组赋值给 this.checkedPeriodArr
        this.checkedPeriodArr = formattedPeriodArray;
        console.log('📋 已赋值给 this.checkedPeriodArr，数量:', this.checkedPeriodArr.length);
        console.log('📋 this.checkedPeriodArr:', this.checkedPeriodArr);
        
        // 🔑 保存B状态选中的数组（用于更新 cooperation.vue 的列表）
        uni.setStorageSync('checkedPeriodArr', JSON.stringify(this.checkedPeriodArr));
        // 保存所有A状态的班期数据（包含选中状态标记）
        uni.setStorageSync('selectedDates', JSON.stringify(allPeriodDates));
        uni.setStorageSync('selectedDatesBForPeriodList', JSON.stringify(this.selectedDatesB));
      } else {
        // 其他情况：将选择的日期数据保存到storage中
        const selectedDates = this.convertDateObjects(this.formattedUserMarkedDates);
        
        // 🔑 打印返回的数据
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('📋 cooperationDateUtilPage - 确认选择（其他模式）');
        console.log('   - 选中的日期:', selectedDates);
        console.log('   - A状态日期列表（selectedDatesA）:', this.selectedDatesA);
        console.log('   - B状态日期列表（selectedDatesB）:', this.selectedDatesB);
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        
        uni.setStorageSync('selectedDates', JSON.stringify(selectedDates));
      }
      
      // 同时保存A和B状态的日期
      uni.setStorageSync('selectedDatesA', JSON.stringify(this.selectedDatesA));
      uni.setStorageSync('selectedDatesB', JSON.stringify(this.selectedDatesB));

      this.BackPage();
    },
    
    // 转换日期对象
    convertDateObjects(arr) {
      return arr.map(item => {
        const year = item.year;
        const month = String(item.month).padStart(2, '0');
        const day = String(item.day).padStart(2, '0');
        const weekDay = item.weekDay;
        const dateStr = `${year}-${month}-${day}`;

        // 尝试从 periodList 中获取 periodId
        let periodId = null;
        if (this.periodList && this.periodList.length > 0) {
          const period = this.periodList.find(p => {
            const pDateStr = this.extractDateFromPeriod(p);
            return pDateStr === dateStr;
          });
          if (period) {
            periodId = period.id || period.periodId;
          }
        }

        return {
          DateName: dateStr,
          Datevalue: dateStr,
          Datevalue1: `${month}/${day}`,
          date: `${month}/${day}`,
          WeekName: `周${weekDay}`,
          id: periodId,
          periodId: periodId,
          mycheck: true,
          is: true,
          isSelected: true
        };
      });
    },

    BackPage() {
      uni.navigateBack({
        delta: 1
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.calendar-container {
  padding: 20rpx;
  padding-bottom: 400rpx;
  background-color: #EDEDED;
  min-height: 100%;
  position: relative;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
}

.confirm-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #1677FF;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(22, 119, 255, 0.3);
  transition: all 0.3s ease;
  margin-bottom: 20rpx;

  &:active {
    transform: scale(0.98);
    background-color: #0d5dd6;
  }
}

.scroll-container {
  padding: 0;
}

.scroll-section {
  margin-bottom: 30rpx;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.scroll-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #555;
  padding-left: 8rpx;
  border-left: 4rpx solid #4caf50;
}

.expand-icon {
  font-size: 32rpx;
  color: #666;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.scroll-view {
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  padding-bottom: 10rpx;
}

.scroll-item {
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 104rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 15rpx;
  text-align: center;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
  border: 1rpx solid #eee;
  padding: 0;
  background-clip: padding-box;
}

.scroll-item.marked {
  background-color: #e8f5e9;
  border-color: #dcedc8;
}

.scroll-date {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 6rpx;
  padding-top: 16rpx;
}

.scroll-week {
  font-size: 22rpx;
  color: #666;
  padding-bottom: 16rpx;
}

.expand-container {
  max-height: calc(2.5 * 120rpx);
  overflow-y: auto;
  margin-top: 10rpx;
  padding-bottom: 10rpx;
}

.expand-row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: flex-start;
  margin-bottom: 0;
  width: 100%;
}

.expand-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 104rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 15rpx;
  margin-bottom: 15rpx;
  text-align: center;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
  border: 1rpx solid #eee;
  padding: 0;
  background-clip: padding-box;
}

.expand-item.marked {
  background-color: #e8f5e9;
  border-color: #dcedc8;
}

.expand-date {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 6rpx;
  padding-top: 16rpx;
}

.expand-week {
  font-size: 22rpx;
  color: #666;
  padding-bottom: 16rpx;
}

.expand-container::-webkit-scrollbar {
  width: 6rpx;
}

.expand-container::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3rpx;
}

@keyframes rotateOpen {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(90deg);
  }
}

@keyframes rotateClose {
  from {
    transform: rotate(90deg);
  }
  to {
    transform: rotate(0deg);
  }
}

.expand-icon .cuIcon-right:not(.fold) {
  animation: rotateOpen 0.3s ease forwards;
}

.expand-icon .cuIcon-right.fold {
  animation: rotateClose 0.3s ease forwards;
}

.expand-icon .cuIcon-right {
  display: inline-block;
  transition: transform 0.3s ease;
  transform-origin: center;
}

.container {
  height: 100vh;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.scrollable-content {
  height: 100%;
  -webkit-overflow-scrolling: touch;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #f8f9fa;
  z-index: 10;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}
</style>

